package com.webserver.core;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class HandlerMapping {
    private static Map<String, MethodMapping> mapping = new HashMap<>();

    static {
        initMapping();
    }

    private static void initMapping() {
        try {
            File dir = new File(
                    HandlerMapping.class.getClassLoader().getResource("./com/webserver/controller").toURI()
            );
            File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
            for (File file : subs) {
                String fileName = file.getName();
                String className = fileName.substring(0, fileName.indexOf("."));
                Class cls = Class.forName("com.webserver.controller." + className);
                if (cls.isAnnotationPresent(Controller.class)) {
                    Object controller = cls.newInstance();
                    Method[] methods = cls.getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.isAnnotationPresent(RequestMapping.class)) {
                            RequestMapping arm = method.getAnnotation(RequestMapping.class);
                            String value = arm.value();

                            MethodMapping mm = new MethodMapping(controller,method);
                            mapping.put(value,mm);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static MethodMapping getMethod(String path){
        return mapping.get(path);
    }


    public static void main(String[] args) {
        MethodMapping mm = getMethod("/myweb/reg");
        Object obj = mm.getController();
        Method method = mm.getMethod();
        System.out.println(obj+":"+method.getName());
    }









    public static class MethodMapping {
        private Object controller;
        private Method method;

        public MethodMapping(Object controller, Method method) {
            this.controller = controller;
            this.method = method;
        }

        public Object getController() {
            return controller;
        }

        public void setController(Object controller) {
            this.controller = controller;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }
    }

}
